package features.advance.leetcode.tree.easy;

import features.advance.leetcode.tree.model.TreeNode;
import features.advance.leetcode.util.TreeUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 *  剑指 Offer 32 - II. 从上到下打印二叉树 II
 *
 *  难度；简单
 *
 * 从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
 *
 *
 *
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回其层次遍历结果：
 *
 * [
 *   [3],
 *   [9,20],
 *   [15,7]
 * ]
 *
 *
 * 提示：
 *
 * 节点总数 <= 1000
 * 注意：本题与主站 102 题相同：https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 *
 * @author LIN
 * @date 2021-06-18
 */
public class Offer32_2 {
    public static void main(String[] args) {
        Solution solution = new Solution() {
            List<List<Integer>> node=new ArrayList();

            @Override
            public List<List<Integer>> levelOrder(TreeNode root) {
                creatInt(root,0);
                return node;
            }

            public void creatInt(TreeNode<Integer> root,int k){
                if(root != null){
                    if(k >= node.size()){
                        node.add(new ArrayList());
                    }
                    node.get(k).add(root.val);
                    creatInt(root.left,k+1);
                    creatInt(root.right,k+1);
                }

            }
        };
        String str = "[3,9,20,1,2,15,7]";
        TreeNode<Integer> root = TreeUtil.stringToTreeNode(str);
        List<List<Integer>> res = solution.levelOrder(root);
        System.out.println(res);
    }

    static class Solution {

        public List<List<Integer>> levelOrder(TreeNode root) {
            Queue<TreeNode<Integer>> queue = new LinkedList<>();
            List<List<Integer>> list = new ArrayList<>();
            if(root == null){
                return list;
            }
            int elementsOfLayer = 0;
            List<Integer> layer = new ArrayList<>();
            if(queue.isEmpty()){
                queue.add(root);
                elementsOfLayer++;
            }
            while(!queue.isEmpty()){
                TreeNode<Integer> poll = queue.poll();
                elementsOfLayer--;

                if(poll.left!=null){
                    queue.add(poll.left);
                }
                if(poll.right!=null){
                    queue.add(poll.right);
                }
                layer.add(poll.val);
                if(elementsOfLayer==0){
                    list.add(layer);
                    layer = new ArrayList<>();
                    elementsOfLayer=queue.size();
                }
            }

            return list;
        }

    }

}
